<?php

namespace app\store\service;
use app\admin\model\Admin;
use think\facade\Db;
use think\facade\Session;

class AdminService
{   

    protected $store_id;
    
    public function __construct()
    {
        $this->store_id = session('store_id');
    }

    public function getMenuList($id)
    {   
        $user = Db::name('admin')->field('id,is_supper')->where(['type'=>2,'id' => $id])->find();

        if(empty($user)){
            return [];
        }

        if(!empty($user['is_supper'])){
    
            $menusCol = Db::name('menu')->where(['type' => 2, 'status' => 1])->select();
    
            $menus = $menusCol->isEmpty() ? [] : $menusCol->toArray();
    
            return $menus;
        }
        
        $menus = $this->getAdminMenu($id);

        return $menus;
        
    }


    protected function getAdminMenu($id)
    {
        $roles = Db::name('admin')->alias('a')
              ->field('c.id')  
              ->join('admin_role b','a.id=b.admin_id')
              ->join('role c','c.id=b.role_id')
              ->where('a.id',$id)
              ->select();

        if($roles->isEmpty()){
            return [];
        }      
                      
        $ids = array_column($roles->toArray(),'id');
        
        $menusCol = Db::name('menu')->field('a.id,a.parent_id,a.title,a.url,a.node,a.display')
                    ->alias('a')
                    ->join('role_menu b','a.id=b.menu_id')
                    ->whereOr(['type' => 2, 'status' => 1])
                    ->whereIn('b.role_id',$ids)
                    ->select();

        if($menusCol->isEmpty()){
            return [];
        } 
        

        $menus = array_unique($menusCol->toArray(),SORT_REGULAR);

        return $menus;
    }

    public function checkUser($username,$password)
    {
        $user = Db::name('admin')->withOutField('create_time,update_time')->where(['username'=> $username,'type' => 2])->find();

        if(empty($user)){
            return false;
        }

        $result = password_verify($password,$user['password']);

        if($result){
            Session::set('user_id',$user['id']);
            Session::set('nickname',$user['nickname']);
            Session::set('avatar',$user['avatar']);
            Session::set('store_id',$user['store_id']);

            return true;
        }

        return false;
    }

    public function getAdminList($keyword)
    {   
        $query = Db::name('admin')->where('store_id',$this->store_id)->withOutField('password');
        if(!empty($keyword)){
            $query->where('nickname',"%$keyword%");
        }

        $admins = $query->paginate(10);
        
        return $admins;
    }

    public function findAdmin($id)
    {   
        $model = new Admin();
        $admin = $model->withOutField('password,create_time,update_time')->find($id);

        return $admin;
    }

    public function getRoleOption($admin_id = false)
    {   
        $roles = Db::name('role')->field('id,name')->where('store_id',$this->store_id)->select();

        if(!$admin_id){
            return $roles;
        }

        $ids =  Db::name('admin_role')->field('role_id')->where('admin_id',$admin_id)->select();
        
        $roleArr = $roles->isEmpty() ? [] : $roles->toArray();
        $idArr = $ids->isEmpty() ? [] : array_column($ids->toArray(),'role_id');
        
        $options = [];
        foreach($roleArr as $k => $v){
            in_array($v['id'],$idArr) ? $v['checked'] = 1 : $v['checked'] = 0;
            $options[$k] = $v;
        }

        return $options;
    }
    
    public function saveAdmin($data)
    {   
        
        $data['store_id'] = $this->store_id;
       
        $model = Admin::create($data);
        $arr = [];

        foreach($data['roles'] as $k => $v){
            $arr[$k]['admin_id'] = $model['id'];
            $arr[$k]['role_id'] = $v;
        }

        $rows = Db::name('admin_role')->insertAll($arr);

        return  $model['id'] && $rows;
    }

    public function updateAdmin($data)
    {
        $model = new Admin();
        
        if(empty($data['password'])){
            unset($data['password']);
        }
        
        $model->update($data);

        foreach($data['roles'] as $k => $v){
            $arr[$k]['admin_id'] = $data['id'];
            $arr[$k]['role_id'] = $v;
        }
        Db::name('admin_role')->where('admin_id',$data['id'])->delete();
        Db::name('admin_role')->insertAll($arr);
        return $model;
    }


    public function changeAdmin($data)
    {
        
        if(empty($data['password'])){
            unset($data['password']);
        }
        
        $model = Admin::update($data);

        session('avatar',$model['avatar']);
        session('nickname',$model['nickname']);
       

        return $model;
    }


    public function deleteAdmin($id)
    {   
        $model = new Admin();
        $res =$model->where('id',$id)->delete();
       
        return $res ? true : false;
    }
}